import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/moudle/refresh/my_refresh.dart';
import 'package:sptapp/page/min/min_add_member_dialog.dart';
import 'package:sptapp/widget/common_widget.dart';

import '../../api/interface/user_api.dart';
import '../../api/request/response_data.dart';
import '../../widget/cache_image.dart';

class MinManageAccessPage extends StatefulWidget {
  final Map arguments;
  const MinManageAccessPage({super.key, required this.arguments});

  @override
  State<MinManageAccessPage> createState() => _MinManageAccessPageState();
}

class _MinManageAccessPageState extends State<MinManageAccessPage> {

  bool isEdit = false;

  late Map grade;
  List users = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getUsers();
  }

  _getUsers()async{
    showLoading();
    ResponseData res = await UserAPI.getUserChild();
    hideLoading();
    if(res.code == 200 && res.data != null){
      users = res.data['userChild']??'';
    }
    if(mounted){
      setState(() {});
    }
  }

  _addUser(){
   SmartDialog.show(builder: (ctx){
     return MinAddMemberDialog(
       callBack: (){
         _getUsers();
       },
     );
   },alignment: Alignment.center,clickMaskDismiss: false);
  }

  _deleteUser(Map user,int index)async{
    Map<String,dynamic> data = {
      'userId': user['user_id']
    };
    ResponseData res = await UserAPI.invitationDel(data);
    if(res.code == 200){
      setState(() {
        users.removeAt(index);
      });
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      appBar: myAppBar(context, 'Manage Access'.tr),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 40.w,),
            Container(
              child: Text('User Access'.tr,style: TextStyle(
                color: Colors.white,
                fontSize: 28.sp,
                fontWeight: FontWeight.w600
              ),),
            ),
            SizedBox(height: 16.w,),
            Container(
              child: Text('If you add a user, that user will have access to all the App features for your energy system.'.tr,style: TextStyle(
                  color: Color.fromRGBO(255, 255, 255, 0.5),
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w400
              ),),
            ),
            SizedBox(height: 34.w,),
            Container(
              width: 670.w,
              height: 1.w,
              color: Color.fromRGBO(255, 255, 255, 0.1),
            ),
            SizedBox(height: 40.w,),
            GestureDetector(
              onTap: (){
                _addUser();
              },
              child: Container(
                width: 670.w,
                height: 108.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: themeColor,
                  borderRadius: BorderRadius.circular(8.w)
                ),
                child: Text('Add Account'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 32.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            Expanded(child: Container(
              child: Column(
                children: [
                  SizedBox(height: 80.w,),
                  Container(
                    height: 116.w,
                    decoration: BoxDecoration(
                      border: Border(bottom: BorderSide(color: Color.fromRGBO(255, 255, 255, 0.1),width: 1.w))
                    ),
                    child: Row(
                      children: [
                        Expanded(child: Text('User Management'.tr,style: TextStyle(
                            color: Colors.white,
                            fontSize: 28.sp,
                            fontWeight: FontWeight.w600
                        ),)),
                        GestureDetector(
                          onTap: (){
                            setState(() {
                              isEdit = !isEdit;
                            });
                          },
                          child: Container(
                            child: Text('Edit'.tr,style: TextStyle(
                                color: themeColor,
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600
                            )),
                          ),
                        )
                      ],
                    ),
                  ),
                  Expanded(child: EasyRefresh(
                    header: myRefreshHeader(),
                    footer: myRefreshFooter(),
                    onRefresh: (){
                      _getUsers();
                    },
                    onLoad: (){
                      _getUsers();
                    },
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          ListView.builder(itemBuilder: (ctx,index){
                            Map user = users[index];
                            return Container(
                              height: 116.w,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  border: Border(bottom: BorderSide(color: Color.fromRGBO(255, 255, 255, 0.1),width: 1.w))
                              ),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Container(
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(16.w),
                                      child: CacheImage(
                                        image: user['avatar']??'assets/home/home_person.png',
                                        width: 48.w,
                                        height: 48.w,
                                        fit: BoxFit.fitWidth,
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: 16.w,),
                                  Expanded(child: Text(user['email']??'',style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 28.sp,
                                      fontWeight: FontWeight.w400
                                  ),maxLines: 1,overflow: TextOverflow.ellipsis,)),
                                  SizedBox(width: 24.w,),
                                  Visibility(child: GestureDetector(
                                    onTap: (){
                                      _deleteUser(user,index);
                                    },
                                    child: Container(
                                      child: Image.asset('assets/common/common_close.png',width: 48.w,),
                                    ),
                                  ),visible: isEdit,)
                                ],
                              ),
                            );
                          },itemCount: users.length,padding: EdgeInsets.zero,shrinkWrap: true,physics: NeverScrollableScrollPhysics(),),
                          SizedBox(height: ScreenUtil().bottomBarHeight+20.h,)
                        ],
                      ),
                    ),
                  ))
                ],
              ),
            ))
          ],
        ),
      ),
    );
  }
}
